﻿/*
 * Copyright © 2020, Wuxi Safover Intelligent Technology Co., Ltd. All rights reserved.
 * 
 * 无锡安永智能科技有限公司版权所有，未经许可，不得用于商业用途
 * 
 * Visit: https://www.safover.com/ 
 */

using System;
using System.IO.Ports;
using Safover.LidarCollector.Core;
using Safover.LidarCollector.Extensions;
using log4net;
using System.Reflection;
using Safover.LidarCollector.Models;

namespace GPS.BeiTian
{
    public class Nema0183GpsLocationDevice : GpsLocatorDevice
    {
        private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        #region Singleton
        public static GpsLocatorDevice Instance { get; } = new Nema0183GpsLocationDevice();

        private Nema0183GpsLocationDevice()
        {
            PortName = "COM2";

            BaudRate = 9600;

            DataBits = 8;

            Parity = Parity.None;

            StopBits = StopBits.One;

            Handshake = Handshake.None;
        }

        #endregion

        public override string DeviceType => "Nema0183GpsLocationDevice";

        public override GpsInformation ObtainGpsInformation()
        {
            DateTime time;
            if (UtcTimestamp != null)
            {
                DateTime utcTime = TimeUtils.Timestamp2UtcTime((long)UtcTimestamp);

                time = TimeUtils.UtcTimeToBeiJingTime(utcTime);
            }
            else
            {
                time = TimeUtils.UtcTimeToBeiJingTime(DateTime.UtcNow);
            }

            return new GpsInformation
            {
                Latitude = RealLatitude == null ? DefaultLatitude : (double)RealLatitude,
                Longitude = RealLongitude == null ? DefaultLongitude : (double)RealLongitude,
                Altitude = RealAltitude == null ? DefaultAltitude : (double)RealAltitude,
                Time = time
            };
        }

        protected override void OnDataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string message = ReadLine();

            if (!message.StartsWith("$GP"))
            {
                Log.Error($"[Nema0183GpsLocationDevice]: Unexpected message=[{message}], device=[{DeviceType}].");
            }

            if (message.StartsWith("$GPGLL"))
            {
                try
                {
                    var segments = message.Split(new char[] { ',' });

                    RealLongitude = double.Parse(segments[5]);

                    RealLatitude = double.Parse(segments[3]);

                    UtcTimestamp = TimeUtils.BeiJingTimeToUtcTimestamp(DateTime.Now);

                    DeviceReadingsUpdated?.Invoke(this, new GpsLocatorReadingsUpdatedEventArgs
                    {
                        Longitude = (double)RealLongitude,
                        Latitude = (double)RealLatitude,

                    });
                }
                catch (Exception ex)
                {
                    Log.Error($"[Nema0183GpsLocationDevice]: Unexpected message=[{message}], device=[{DeviceType}].", ex);
                }
            }
        }
    }
}
